import { login, logout, getInfo, refreshToken } from '@/api/login'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    userInfo:'',
    searchRegionId:0
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_USERINFO:(state, userInfo)=>{
      state.userInfo = userInfo
    },
    SET_SEARCHREGIONID:(state, devRegionId)=>{
      state.searchRegionId = devRegionId
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          let data = res.data
          // setToken("123")
          // commit('SET_TOKEN', "123")
          // setExpiresIn(2608707826467)
          // commit('SET_EXPIRES_IN', 2608707826467)
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          setExpiresIn(data.expiresIn)
          commit('SET_EXPIRES_IN', data.expiresIn)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          // res = {
          //   "msg": "操作成功",
          //   "code": 200,
          //   "permissions": ["*:*:*"],
          //   "roles": ["admin"],
          //   "user": {
          //     "searchValue": null,
          //     "createBy": "admin",
          //     "createTime": "2020-11-20 19:29:42",
          //     "updateBy": null,
          //     "updateTime": null,
          //     "remark": "管理员",
          //     "params": {},
          //     "userId": 1,
          //     "deptId": 103,
          //     "userName": "admin",
          //     "nickName": "若依",
          //     "email": "ry@163.com",
          //     "phonenumber": "15888888888",
          //     "sex": "1",
          //     "avatar": "",
          //     "salt": null,
          //     "status": "0",
          //     "delFlag": "0",
          //     "loginIp": "127.0.0.1",
          //     "loginDate": "2020-11-20T19:29:42.000+0800",
          //     "dept": {
          //       "searchValue": null,
          //       "createBy": null,
          //       "createTime": null,
          //       "updateBy": null,
          //       "updateTime": null,
          //       "remark": null,
          //       "params": {},
          //       "deptId": 103,
          //       "parentId": 101,
          //       "ancestors": null,
          //       "deptName": "研发部门",
          //       "orderNum": "1",
          //       "leader": "若依",
          //       "phone": null,
          //       "email": null,
          //       "status": "0",
          //       "delFlag": null,
          //       "parentName": null,
          //       "children": []
          //     },
          //     "roles": [{
          //       "searchValue": null,
          //       "createBy": null,
          //       "createTime": null,
          //       "updateBy": null,
          //       "updateTime": null,
          //       "remark": null,
          //       "params": {},
          //       "roleId": 1,
          //       "roleName": "超级管理员",
          //       "roleKey": "admin",
          //       "roleSort": "1",
          //       "dataScope": "1",
          //       "menuCheckStrictly": false,
          //       "deptCheckStrictly": false,
          //       "status": "0",
          //       "delFlag": null,
          //       "flag": false,
          //       "menuIds": null,
          //       "deptIds": null,
          //       "admin": true
          //     }],
          //     "roleIds": null,
          //     "postIds": null,
          //     "admin": true
          //   }
          // }
          // const user = res
          const avatar = res.data.avatar == "" ? require("@/assets/image/profile.jpg") : res.data.avatar;
          if (res.data.roleNames && res.data.roleNames.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.data.roleNames)
            commit('SET_PERMISSIONS', res.data.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', res.data.userName)
          commit('SET_AVATAR',res.data.avatar)
          commit('SET_USERINFO',res.data)
          commit('SET_SEARCHREGIONID',res.data.devRegionId)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 刷新token
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        refreshToken(state.token).then(res => {
          setExpiresIn(res.data)
          commit('SET_EXPIRES_IN', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
